<template>
  <view class="detail-container">
    <!-- 导航栏 -->
    <view class="nav-tabs">
      <view class="nav-tab" :class="{ active: activeTab === 'basic' }" @click="switchTab('basic')">
        基本信息
      </view>
      <view class="nav-tab" :class="{ active: activeTab === 'records' }" @click="switchTab('records')">
        维修调拨记录
      </view>
    </view>

    <!-- 基本信息页面 -->
    <view v-if="activeTab === 'basic'" class="basic-info">
      <view class="info-card">
        <view class="info-section">
          <view class="section-title">设备信息</view>
          <view class="info-grid">
            <view class="info-item">
              <text class="info-label">设备名称</text>
              <text class="info-value">{{ deviceInfo.equipmentName || deviceInfo.name || '未知' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">设备编号</text>
              <text class="info-value">{{ deviceInfo.equipmentCode || deviceInfo.code || '未知' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">设备型号</text>
              <text class="info-value">{{ deviceInfo.model || '未知' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">出厂编号</text>
              <text class="info-value">{{ deviceInfo.serialNumber || '未知' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">数量</text>
              <text class="info-value">{{ deviceInfo.quantity || '未知' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">单位</text>
              <text class="info-value">{{ deviceInfo.unit || '未知' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">设备所在地</text>
              <text class="info-value">{{ deviceInfo.location || '未知' }}</text>
            </view>
            <view class="info-item">
              <text class="info-label">设备状态</text>
              <text class="info-value status" :class="statusClass">{{ statusText }}</text>
            </view>
          </view>
        </view>

        <view class="info-section" v-if="deviceInfo.remark">
          <view class="section-title">备注</view>
          <view class="remark-content">
            <text class="remark-text">{{ deviceInfo.remark }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 维修调拨记录页面 -->
    <view v-if="activeTab === 'records'" class="records-info">
      <view class="records-card">
        <view class="timeline-container">
          <view v-if="timelineData.length === 0" class="empty-state">
            <text class="empty-text">暂无记录</text>
          </view>
          <view v-else class="timeline">
            <view v-for="(item, index) in timelineData" :key="index" class="timeline-item">
              <view class="timeline-dot" :class="item.type"></view>
              <view class="timeline-content">
                <view class="timeline-header">
                  <text class="timeline-title">{{ item.title }}</text>
                  <text class="timeline-time">{{ item.date }}</text>
                </view>
                <view class="timeline-body">
                  <view v-if="item.type === 'maintenance'" class="maintenance-desc">
                    <view class="desc-item">
                      <text class="desc-label">维修问题点：</text>
                      <text class="desc-value">{{ item.repairIssues }}</text>
                    </view>
                    <view class="desc-item">
                      <text class="desc-label">状态描述：</text>
                      <text class="desc-value">{{ item.desc }}</text>
                    </view>
                    <view class="desc-item">
                      <text class="desc-label">维修记录：</text>
                      <text class="desc-value">{{ item.repairRecords }}</text>
                    </view>
                    <view class="desc-item" v-if="item.expectedCompletionTime">
                      <text class="desc-label">预计完成时间：</text>
                      <text class="desc-value">{{ item.expectedCompletionTime }}</text>
                    </view>
                  </view>
                  <view v-else-if="item.type === 'transfer'" class="transfer-desc">
                    <view class="desc-item">
                      <text class="desc-label">调出地点：</text>
                      <text class="desc-value">{{ item.from }}</text>
                    </view>
                    <view class="desc-item">
                      <text class="desc-label">调入地点：</text>
                      <text class="desc-value">{{ item.to }}</text>
                    </view>
                    <view class="desc-item" v-if="item.remark">
                      <text class="desc-label">备注：</text>
                      <text class="desc-value">{{ item.remark }}</text>
                    </view>
                  </view>
                </view>
                <view class="timeline-footer">
                  <view class="status-tag" :class="item.type">
                    <text class="status-text">{{ item.type === 'maintenance' ? '设备维修' : '设备调拨' }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getEquipment, getRepairHistoryList, getTransferRecordsList } from '@/api/equipment/main'

export default {
  data() {
    return {
      equipmentId: null,
      deviceInfo: {},
      activeTab: 'basic',
      timelineData: [],
      loading: false
    }
  },
  computed: {
    // 状态文本
    statusText() {
      const statusMap = {
        1: '在线',
        2: '离线',
        3: '告警',
        4: '待报废',
        5: '维修中',
        6: '已报废'
      }
      return statusMap[this.deviceInfo.status] || statusMap[String(this.deviceInfo.status)] || '未知'
    },
    // 状态样式类
    statusClass() {
      const classMap = {
        1: 'status-online',
        2: 'status-offline',
        3: 'status-alarm',
        4: 'status-pending',
        5: 'status-repairing',
        6: 'status-scrapped'
      }
      return classMap[this.deviceInfo.status] || classMap[String(this.deviceInfo.status)] || 'status-unknown'
    }
  },
  async onLoad(options) {
    if (options.id) {
      this.equipmentId = options.id
      await this.fetchDeviceInfo()
    } else {
      uni.showToast({
        title: '缺少设备ID',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },
  methods: {
    // 获取设备信息
    async fetchDeviceInfo() {
      try {
        uni.showLoading({
          title: '加载中...'
        })
        const res = await getEquipment(this.equipmentId)
        const data = res && res.data ? res.data : res
        this.deviceInfo = data
        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
        console.error('获取设备信息失败:', error)
        uni.showToast({
          title: '获取设备信息失败',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },

    // 切换标签页
    switchTab(tab) {
      this.activeTab = tab
      if (tab === 'records' && this.timelineData.length === 0) {
        this.fetchRecords()
      }
    },

    // 获取维修和调拨记录
    async fetchRecords() {
      if (this.loading) return

      this.loading = true
      try {
        uni.showLoading({
          title: '加载记录中...'
        })

        // 并行获取维修记录和调拨记录
        const [repairRes, transferRes] = await Promise.all([
          getRepairHistoryList({ equipmentId: this.equipmentId }),
          getTransferRecordsList({ equipmentId: this.equipmentId })
        ])

        // 处理维修记录
        const repairLogs = (repairRes.rows || repairRes.data || []).map(item => ({
          date: this.formatTime(item.createTime),
          title: '设备维修',
          repairIssues: item.repairIssues || '',
          repairRecords: item.repairRecords || '',
          expectedCompletionTime: item.expectedCompletionTime || '',
          desc: item.statusDescription || '',
          remark: item.remark || '',
          type: 'maintenance'
        }))

        // 处理调拨记录
        const transferLogs = (transferRes.rows || transferRes.data || []).map(item => ({
          date: this.formatTime(item.createTime),
          title: '设备调拨',
          from: item.transferOutLocation || '',
          to: item.transferInLocation || '',
          remark: item.remark || '',
          type: 'transfer'
        }))

        // 合并并按时间降序排序
        this.timelineData = [...repairLogs, ...transferLogs].sort((a, b) =>
          new Date(b.date) - new Date(a.date)
        )

        uni.hideLoading()
      } catch (error) {
        uni.hideLoading()
        console.error('获取记录失败:', error)
        uni.showToast({
          title: '获取记录失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return ''
      const date = new Date(time)
      if (isNaN(date.getTime())) return time

      const pad = n => n < 10 ? '0' + n : n
      const y = date.getFullYear()
      const m = pad(date.getMonth() + 1)
      const d = pad(date.getDate())
      const h = pad(date.getHours())
      const min = pad(date.getMinutes())
      const s = pad(date.getSeconds())

      return `${y}-${m}-${d} ${h}:${min}:${s}`
    }
  }
}
</script>

<style lang="scss" scoped>
.detail-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

// 导航栏样式
.nav-tabs {
  display: flex;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  position: sticky;
  top: 0;
  z-index: 10;
}

.nav-tab {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  font-size: 28rpx;
  color: #666;
  position: relative;
  transition: all 0.3s ease;
}

.nav-tab.active {
  color: #007AFF;
  font-weight: 600;
}

.nav-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: #007AFF;
  border-radius: 2rpx;
}

// 基本信息页面样式
.basic-info {
  padding: 20rpx;
}

.info-card {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.info-section {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.info-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 32rpx;
  background: #007AFF;
  border-radius: 3rpx;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30rpx;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.info-label {
  font-size: 24rpx;
  color: #999;
  font-weight: 500;
}

.info-value {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  word-break: break-all;
}

.info-value.status {
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
  display: inline-block;
  width: fit-content;

  &.status-online {
    color: #34C759;
    background-color: #E8F5E8;
  }

  &.status-offline {
    color: #8E8E93;
    background-color: #F0F0F0;
  }

  &.status-alarm {
    color: #FF3B30;
    background-color: #FFE8E8;
  }

  &.status-pending {
    color: #FF9500;
    background-color: #FFF4E6;
  }

  &.status-repairing {
    color: #FF2D92;
    background-color: #FFE8F5;
  }

  &.status-scrapped {
    color: #5856D6;
    background-color: #E8E8FF;
  }

  &.status-unknown {
    color: #8E8E93;
    background-color: #F0F0F0;
  }
}

.remark-content {
  background: #f9f9f9;
  padding: 20rpx;
  border-radius: 12rpx;
  border: 1rpx solid #eee;
}

.remark-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}

// 记录页面样式
.records-info {
  padding: 20rpx;
}

.records-card {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.timeline-container {
  padding: 30rpx;
}

.empty-state {
  text-align: center;
  padding: 80rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.timeline {
  position: relative;
}

.timeline::before {
  content: '';
  position: absolute;
  left: 20rpx;
  top: 0;
  bottom: 0;
  width: 2rpx;
  background: #eee;
}

.timeline-item {
  position: relative;
  padding-left: 80rpx;
  margin-bottom: 40rpx;
}

.timeline-item:last-child {
  margin-bottom: 0;
}

.timeline-dot {
  position: absolute;
  left: 12rpx;
  top: 20rpx;
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  border: 4rpx solid #fff;
  box-shadow: 0 0 0 2rpx #eee;
}

.timeline-dot.maintenance {
  background: #FF3B30;
  box-shadow: 0 0 0 2rpx #FF3B30;
}

.timeline-dot.transfer {
  background: #007AFF;
  box-shadow: 0 0 0 2rpx #007AFF;
}

.timeline-content {
  background: #f9f9f9;
  border-radius: 12rpx;
  padding: 24rpx;
  border: 1rpx solid #eee;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.timeline-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.timeline-time {
  font-size: 24rpx;
  color: #999;
}

.timeline-body {
  margin-bottom: 16rpx;
}

.desc-item {
  display: flex;
  margin-bottom: 12rpx;
  line-height: 1.6;
}

.desc-item:last-child {
  margin-bottom: 0;
}

.desc-label {
  font-size: 24rpx;
  color: #666;
  min-width: 160rpx;
  flex-shrink: 0;
}

.desc-value {
  font-size: 24rpx;
  color: #333;
  flex: 1;
  word-break: break-all;
}

.timeline-footer {
  display: flex;
  justify-content: flex-end;
}

.status-tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
}

.status-tag.maintenance {
  background: #FFE8E8;
  color: #FF3B30;
}

.status-tag.transfer {
  background: #E8F0FF;
  color: #007AFF;
}

.status-text {
  font-weight: 500;
}

// 响应式设计
@media (max-width: 750rpx) {
  .info-grid {
    grid-template-columns: 1fr;
    gap: 20rpx;
  }

  .timeline-item {
    padding-left: 60rpx;
  }

  .timeline::before {
    left: 15rpx;
  }

  .timeline-dot {
    left: 7rpx;
  }
}
</style>
